package cn.cosmosx.base.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import cn.cosmosx.base.helper.CurrentThreadContextHelper;
import cn.cosmosx.base.helper.SessionHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求入口第一道防线过滤器
 * 用于资源加载，资源释放等操作
 * 该过滤器建议加在其他过滤器之前
 */
@Component
public class RequestEntryFinalKeeperFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } finally {
            this.clearAllCaches();
        }
    }

    /**
     * 清除资源
     */
    private void clearAllCaches() {
        SessionHelper.clear();
        CurrentThreadContextHelper.clear();
    }
}
